<?php
namespace app\task\controller;

use hema\wechat\WxBizMsgCrypt;
use hema\wechat\Driver;
use app\task\model\Config as ConfigModel;
use app\task\model\Applet as AppletModel;
use app\task\model\Wechat as WechatModel;
use app\task\model\Apply as ApplyModel;
use app\task\model\UserDetail as UserDetailModel;

/**
 * 第三方平台与微信通讯接口
 */

class Callback
{
    /**
     * 异步通知处理
     */
    public function ticket()
    {
		// 接收公众号平台发送的消息
		$timeStamp = empty ( $_GET ['timestamp']) ? '' : trim ( $_GET ['timestamp'] );//时间戳
        $nonce = empty ( $_GET ['nonce'] ) ? '' : trim ( $_GET ['nonce'] );//随机数
        $msg_signature = empty ( $_GET['msg_signature'] ) ? '' : trim ( $_GET ['msg_signature'] );//签名
		$encrypt_type = empty ( $_GET['encrypt_type'] ) ? '' : trim ( $_GET ['encrypt_type'] );//加密类型，为 aes
        $encryptMsg = file_get_contents ('php://input' );
        //创建解密类
		$pc = new WxBizMsgCrypt();
		$msg = '';
		$errCode = $pc->decryptMsg($msg_signature, $timeStamp, $nonce, $encryptMsg, $msg);
		if($errCode == 0){
			$data = _xml_to_arr($msg);	//XML转换为数组
			//write_log($data, __DIR__);//用于测试callback.php接口
			//推送的ticket
			if($data['InfoType'] == 'component_verify_ticket'){
				//获取第三方配置信息
				$config = ConfigModel::detail();
				$config->component_verify_ticket = $data['ComponentVerifyTicket']; 
				//更新过期的令牌component_access_token
				if($config['expires_in'] < time()){
					//过期更新access_token
					$wx = new Driver;
					$token = $wx->getComponentToken($data['ComponentVerifyTicket']);
					if(isset($token['component_access_token'])){
						$config->component_access_token = $token['component_access_token'];
						$config->expires_in = time()+3600;
					}
				}
				$config->save();	//保存ticket
				die('success');
			}
			//取消授权
			if($data['InfoType'] == 'unauthorized'){
				if($wechat = WechatModel::getWechat(['app_id' => $data['AuthorizerAppid']])){
					$wechat->save(['status' => 0]);
				}
				if($wxapp = AppletModel::getApplet(['app_id' => $data['AuthorizerAppid']])){
					$wxapp->save(['status' => 0]);
				}
				die('success');
			}
			//更新授权
			if($data['InfoType'] == 'updateauthorized'){
				/*
				Array
				(
					[AppId] => wxd081a139beb02c77
					[CreateTime] => 1572001402
					[InfoType] => updateauthorized
					[AuthorizerAppid] => wxfd9875920f95854c
					[AuthorizationCode] => queryauthcode@@@x51tQWCqAh2vrSm6LOkLUDEvazWHdq8bZ05mwEwMDVGCBVZiydGjEMhbO0qDTriq-7F1sFNuicI_lqSp4SWUqg
					[AuthorizationCodeExpiredTime] => 1572005002
					[PreAuthCode] => preauthcode@@@eJqcbkFUN6N1hrO1S4H_zymHzftXj902fhTR5EM1zUCFHCUmSYISd-dYq_Gt_x0w
				)
				*/
			}
			
			/*
			//成功授权
			if($data['InfoType'] == 'authorized'){
				
			}
			*/
			//小程序注册成功
			if($data['InfoType'] == 'notify_third_fasteregister'){
				//验证状态
				$this->fasteregister($data);
				die('success');				
			}
			die('success');
		}else{
			//write_log('Callback 解密失败，code：'.$errCode, __DIR__);
		}
    }
	
	
	
	/**
     * 快速注册小程序状态验证
    */
	private function fasteregister(array $data)
	{
		//第一步、获取申请者资料
		$detail = UserDetailModel::getDetail([
			'merchant_name' => $data['info']['name'],
			'license_number' => $data['info']['code'],
			'legal_persona_wechat' => $data['info']['legal_persona_wechat'],
			'id_card_name' => $data['info']['legal_persona_name']
		]);
		//第二步、获取到了资料
		if($detail){
			//第三步、查询申请记录
			$apply = ApplyModel::where('apply_mode','<',30)->where([
				'user_id' => $detail['user_id'],
				'apply_status' => 20
			])->order('apply_id','desc')->find();
			//如果查询到了申请记录
			if($apply){
				//判断微信端审核状态
				if($data['status'] == 0){
					//审核成功 - 获取授权信息
					$wx = new Driver;
					$result = $wx->getAuth($data['auth_code']);
					$auth = $result['authorization_info'];//得到授权信息
					//获取授权应用的帐号基本信息
					$result = $wx->getAppInfo($auth['authorizer_appid']);
					$app = $result['authorizer_info'];//得到授权应用的帐号基本信息
					$api_domain = '';
                    $signature = '';
                    //添加服务器域名
                    $serveDomain = $wx->setServeDomain(0,'',$auth['authorizer_access_token']);
                    if($serveDomain['errcode'] == 0){
                        $api_domain = $serveDomain['apiurl'];
                    }
                    //设置小程序简介
                    $setSignature = $wx->setSignature(0,'',$auth['authorizer_access_token']);
                    if($setSignature['errcode'] == 0){
                        $signature = $setSignature['signature'];
                    }
					$appletData = [
						'user_name' => $app['user_name'],					//原始ID
						'principal_name' => $app['principal_name'],			//主体名称
						'app_id' => $auth['authorizer_appid'],				//授权方APPid
						'access_token' => $auth['authorizer_access_token'],	//令牌
						'expires_in' => time()+7000,						//令牌过期时间
						'authorizer_refresh_token' => $auth['authorizer_refresh_token'],	//刷新令牌
						'status' => 1,	//是否授权
						'source' => 20 //注册来源
					];
					//判断是平台入驻还是小程序注册
					if(empty($apply['applet_id'])){
						//入驻
						$title = '商户入驻';
						$msg = '入驻成功';
						//新增小程序
						$appletData['app_type'] = 'food';
						$appletData['shop_mode'] = 10;//单门店
						$appletData['user_id'] = $apply['user_id'];
						$appletData['expire_time'] = strtotime('+1year');
						$model = new AppletModel;
						$apply->applet_id = $model->add($appletData,'apply');
					}else{
						//注册
						$title = '注册微信小程序';
						$msg = '注册成功';
						//更新小程序信息
						$model = AppletModel::getApplet(['applet_id' => $apply['applet_id']]); //获取商户数据
						$model->edit($appletData,'apply');
					}
					$apply->apply_status = 30;
				}else{
					//审核失败 (驳回操作)
					$status = [
						100001 => '已下发的模板消息法人并未确认且已超时（24h），未进行身份证校验',
						100002 => '已下发的模板消息法人并未确认且已超时（24h），未进行人脸识别校验',
						100003 => '已下发的模板消息法人并未确认且已超时（24h）',
						101 => '工商数据返回：“企业已注销”',
						102 => '工商数据返回：“企业不存在或企业信息未更新”',
						103 => '工商数据返回：“企业法定代表人姓名不一致”',
						104 => '工商数据返回：“企业法定代表人身份证号码不一致”',
						105 => '法定代表人身份证号码，工商数据未更新，请 5-15 个工作日之后尝试',
						1000 => '工商数据返回：“企业信息或法定代表人信息不一致”',
						1001 => '主体创建小程序数量达到上限',
						1002 => '主体违规命中黑名单',
						1003 => '管理员绑定账号数量达到上限',
						1004 => '管理员违规命中黑名单',
						1005 => '管理员手机绑定账号数量达到上限',
						1006 => '管理员手机号违规命中黑名单',
						1007 => '管理员身份证创建账号数量达到上限',
						1008 => '管理员身份证违规命中黑名单'
					];
					if($data['status'] == -1){
						$apply->reject = '企业与法人姓名不一致';
					}else{
						if(isset($status[$data['status']])){
							$apply->reject = $status[$data['status']];
						}else{
							$apply->reject = '未知原因';
						}
					}	
					$apply->apply_status = 40;
					//判断是平台入驻还是小程序注册
					if(empty($apply['applet_id'])){
						//入驻
						$title = '商户入驻 - 被驳回';
						$msg = '入驻失败';
					}else{
						//注册
						$title = '注册小程序 - 被驳回';
						$msg = '注册失败';
					}
				}
			}
			//发送微信通知
			sand_examine_msg($apply['apply_id'],$title,$msg,$apply['user_id']);
			$apply->save();
		}
		return true;
	}
}
